#include "udp.h"

Udp::Udp(QObject *parent)
    : QObject{parent}
{

}

Udp::~Udp(){

   // qDebug()<<"udpsocket close1";
    if (udpSocket) {
        // 关闭 UDP 套接字
        udpSocket->close();
        delete udpSocket;
        udpSocket = nullptr;
      //  qDebug()<<"udpsocket close2";
    }
}

void Udp::initSocket()
{
    udpSocket = new QUdpSocket(this);
   // udpSocket->bind(QHostAddress::LocalHost, 1883);
    udpSocket->bind(QHostAddress("172.16.4.203"), 8080);
    //qDebug()<<"start test";

    connect(udpSocket, &QUdpSocket::readyRead,
            this, &Udp::readPendingDatagrams);


}

void Udp::send()
{
    udpSocket->writeDatagram("Hello, World!", 13, QHostAddress("172.16.4.203"), 8080);
    //发送数据到我们指定的udp端口，测试通过
}

void Udp::readPendingDatagrams()
{
     qDebug()<<"receive";
    while (udpSocket->hasPendingDatagrams()) {

        QNetworkDatagram datagram = udpSocket->receiveDatagram();
        // 获取数据
        QByteArray data = datagram.data();

        // 解析数据（例如，如果数据是字符串）
        QString receivedString = QString::fromUtf8(data);
        qDebug()<<receivedString;
    }
}


